/*
 * @Description: 
 * @Author: paddies
 * @Date: 2024-12-23 16:15:49
 * @LastEditors: paddies
 * @LastEditTime: 2024-12-30 16:20:24
 * @FilePath: /shared_components/lib/build-vconsole/buildVConsole.dart
 */
import 'dart:convert';

import 'package:colored_json/colored_json.dart';
import 'package:flutter/material.dart';
import 'package:flutter_json_view/flutter_json_view.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:shared_components/build-common/buildCommon.dart';
import 'package:shared_components/build-line/buildLine.dart';
import 'package:shared_components/build-log/buildLog.dart';

Color watchColor = Color(0xff487fd5);
Color errorColor = Colors.red;
Color oldColor = Color(0xff2d313b);

buildVConsole() {
  var list = [].obs;
  list.value = getHttpLogList().reversed.toList();
  // var topHeight = MediaQuery.of(context).size.width;
  var topHeight = MediaQuery.of(Get.overlayContext!).padding.top;
  var bottomHeight = MediaQuery.of(Get.overlayContext!).padding.bottom;

  Get.bottomSheet(
      isScrollControlled: true,
      Container(
        width: double.infinity,
        height: 700,
        color: Colors.white,
        child: Obx(() => Column(
              children: [
                // SizedBox(
                //   height: topHeight,
                // ),
                Container(
                  width: double.infinity,
                  height: 50,
                  color: Colors.white,
                  padding: EdgeInsets.only(left: 10, right: 10),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Text("HTTP请求"),
                      GestureDetector(
                        onTap: () {
                          cleanHttpLog();
                          list.value = getHttpLogList().reversed.toList();
                        },
                        child: Text(
                          "清空",
                          style: TextStyle(color: Color(0xff606671)),
                        ),
                      )
                    ],
                  ),
                ),
                buildLine(),
                Expanded(
                    child: RefreshIndicator(
                        onRefresh: () async {
                          list.value = getHttpLogList().reversed.toList();
                          // controller.onRefresh();
                        },
                        child: Container(
                          width: double.infinity,
                          height: double.infinity,
                          color: Colors.white,
                          padding: EdgeInsets.all(10),
                          child: SingleChildScrollView(
                            physics: const AlwaysScrollableScrollPhysics(),
                            child: Column(
                              children: [
                                // Text(showText(list.length)),
                                ...list.value.map((item) {
                                  var watch = false.obs;
                                  watch.value = item["watch"];
                                  // watch.value = false;
                                  return GestureDetector(
                                    onTap: () {
                                      watch.value = true;
                                      buildLogDetail(item);
                                    },
                                    child: Container(
                                      width: double.infinity,
                                      height: 50,
                                      color: Colors.white,
                                      alignment: Alignment.center,
                                      child: Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        crossAxisAlignment:
                                            CrossAxisAlignment.center,
                                        children: [
                                          Visibility(
                                              visible:
                                                  showText(item["endTime"]) !=
                                                      "",
                                              child: Icon(
                                                  Icons.turned_in_not_rounded,
                                                  color: item["isError"]
                                                      ? errorColor
                                                      : (watch.value == false
                                                          ? watchColor
                                                          : oldColor))),
                                          Visibility(
                                              visible:
                                                  showText(item["endTime"]) ==
                                                      "",
                                              child: Container(
                                                  width: 20,
                                                  height: 20,
                                                  child:
                                                      CircularProgressIndicator(
                                                    strokeWidth: 2,
                                                  ))),
                                          SizedBox(
                                            width: 5,
                                          ),
                                          Text(
                                            showText(item["method"]),
                                            style: TextStyle(
                                                color: item["isError"]
                                                    ? errorColor
                                                    : (watch.value == false
                                                        ? watchColor
                                                        : oldColor)),
                                          ),
                                          SizedBox(
                                            width: 5,
                                          ),
                                          Expanded(
                                              child: Container(
                                            width: double.infinity,
                                            height: double.infinity,
                                            alignment: Alignment.centerLeft,
                                            child: Text(
                                              showText(item["path"]),
                                              style: TextStyle(
                                                  color: item["isError"]
                                                      ? errorColor
                                                      : (watch.value == false
                                                          ? watchColor
                                                          : oldColor)),
                                            ),
                                          )),
                                          Container(
                                            width: 60,
                                            alignment: Alignment.center,
                                            child: Text(
                                              buildFormatTime(int.parse(
                                                  showText(item["startTime"]))),
                                              style: TextStyle(
                                                  fontSize: 12,
                                                  color: item["isError"]
                                                      ? errorColor
                                                      : (watch.value == false
                                                          ? watchColor
                                                          : oldColor)),
                                            ),
                                          )
                                        ],
                                      ),
                                    ),
                                  );
                                }).toList()
                              ],
                            ),
                          ),
                        ))),
                SizedBox(
                  height: bottomHeight,
                )
                // Expanded(
                //     child: Container(
                //   width: double.infinity,
                //   height: double.infinity,
                //   color: Colors.yellow,
                //   child: Text(showText(f)),
                // ))
              ],
            )),
      ));
}

buildLogDetail(dynamic item) {
  var activeTab = 0.obs;
  var activeColor = Color(0xff5f8af7);
  var defaultColor = Color(0xff020101);
  changeWatchLog(item);
  Get.bottomSheet(
      isScrollControlled: true,
      Container(
        width: double.infinity,
        height: 700,
        color: Colors.white,
        child: Obx(() => Column(
              children: [
                Container(
                  width: double.infinity,
                  height: 45,
                  color: Colors.white,
                  child: SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: Row(
                      children: [
                        GestureDetector(
                          onTap: () {
                            activeTab.value = 0;
                          },
                          child: Container(
                            width: 70,
                            height: double.infinity,
                            color: Colors.white,
                            alignment: Alignment.center,
                            child: Text(
                              "概要",
                              style: TextStyle(
                                  color: activeTab.value == 0
                                      ? activeColor
                                      : defaultColor),
                            ),
                          ),
                        ),
                        GestureDetector(
                          onTap: () {
                            activeTab.value = 1;
                          },
                          child: Container(
                            width: 70,
                            height: double.infinity,
                            color: Colors.white,
                            alignment: Alignment.center,
                            child: Text(
                              "请求",
                              style: TextStyle(
                                  color: activeTab.value == 1
                                      ? activeColor
                                      : defaultColor),
                            ),
                          ),
                        ),
                        GestureDetector(
                          onTap: () {
                            activeTab.value = 2;
                          },
                          child: Container(
                            width: 70,
                            height: double.infinity,
                            color: Colors.white,
                            alignment: Alignment.center,
                            child: Text(
                              "响应",
                              style: TextStyle(
                                  color: activeTab.value == 2
                                      ? activeColor
                                      : defaultColor),
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                ),
                buildLine(),
                Expanded(
                    child: Container(
                  width: double.infinity,
                  height: double.infinity,
                  color: Colors.white,
                  padding: EdgeInsets.all(10),
                  child: Column(
                    children: [
                      Visibility(
                          visible: activeTab.value == 0,
                          child: buildGaiYao(item)),
                      Visibility(
                          visible: activeTab.value == 1,
                          child: Expanded(child: buildQingQiu(item))),
                      Visibility(
                          visible: activeTab.value == 2,
                          child: Expanded(
                            child: buildXiangYing(item),
                          ))
                    ],
                  ),
                ))
              ],
            )),
      ));
}

buildGaiYao(dynamic item) {
  return SingleChildScrollView(
    child: Column(
      children: [
        Container(
          width: double.infinity,
          alignment: Alignment.topLeft,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Container(
                width: 90,
                alignment: Alignment.center,
                child: Text("请求地址:"),
              ),
              Expanded(child: Text(showText(item["url"])))
            ],
          ),
        ),
        Container(
          width: double.infinity,
          alignment: Alignment.topLeft,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                width: 90,
                alignment: Alignment.center,
                child: Text("请求方法:"),
              ),
              Expanded(child: Text(showText(item["method"])))
            ],
          ),
        ),
        Container(
          width: double.infinity,
          alignment: Alignment.topLeft,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                width: 90,
                alignment: Alignment.center,
                child: Text("请求时间:"),
              ),
              Expanded(
                  child: Text(DateFormat('yyyy-MM-dd HH:mm:ss').format(
                      DateTime.fromMillisecondsSinceEpoch(item["startTime"]))))
            ],
          ),
        ),
        Container(
          width: double.infinity,
          alignment: Alignment.topLeft,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                width: 90,
                alignment: Alignment.center,
                child: Text("响应时间:"),
              ),
              Expanded(
                  child: Text(DateFormat('yyyy-MM-dd HH:mm:ss').format(
                      DateTime.fromMillisecondsSinceEpoch(item["endTime"]))))
            ],
          ),
        )
      ],
    ),
  );
}

buildQingQiu(dynamic item) {
  return Container(
      width: double.infinity,
      height: double.infinity,
      color: Colors.white,
      child: SingleChildScrollView(
        child: Column(
          children: [
            Visibility(
                visible: showText(item["queryParameters"]) != '{}',
                child: Container(
                  width: double.infinity,
                  alignment: Alignment.topLeft,
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      // Container(
                      //   width: 90,
                      //   alignment: Alignment.center,
                      //   child: Text("参数:"),
                      // ),
                      Expanded(
                          child: buildFormatJson(
                              (jsonEncode(item["queryParameters"]))))
                    ],
                  ),
                )),
            Visibility(
                visible: showText(item["data"]) != "{}" &&
                    showText(item["data"]) != "" &&
                    item["data"] != null,
                child: Container(
                  width: double.infinity,
                  alignment: Alignment.topLeft,
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Expanded(
                          child: buildFormatJson((jsonEncode(item["data"]))))
                    ],
                  ),
                ))
          ],
        ),
      ));
}

buildXiangYing(dynamic item) {
  if (showText(item["endTime"]) == "") {
    return Container(
        width: double.infinity,
        height: double.infinity,
        padding: EdgeInsets.all(10),
        alignment: Alignment.topLeft,
        child: Text(
          "接口请求中",
          style: TextStyle(),
        ));
  }
  if (item["isError"]) {
    return Container(
        width: double.infinity,
        height: double.infinity,
        padding: EdgeInsets.all(10),
        alignment: Alignment.topLeft,
        child: Text(
          showText(item["errorMessage"]),
          style: TextStyle(color: Colors.red),
        ));
  }
  return Container(
      width: double.infinity,
      height: double.infinity,
      color: Colors.white,
      child: SingleChildScrollView(
        child: buildFormatJson(item["body"]),
      ));
}

buildFormatJson(dynamic j) {
  return SingleChildScrollView(
    scrollDirection: Axis.horizontal,
    child: ColoredJson(
      data: showText(j),
    ),
    // child: JsonView.string(
    //   showText(j),
    //   theme: const JsonViewTheme(errorWidget: Text("null")),
    // ),
  );
}

buildFormatTime(int t) {
  var res = "";
  // int timestamp = 1688000000000; // 这里替换为实际的时间戳值
  DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(t);
  Duration difference = DateTime.now().difference(dateTime);
  if (difference.inSeconds < 10) {
    res = "刚刚";
  } else if (difference.inSeconds >= 10 && difference.inSeconds < 30) {
    // print('1分钟前');
    res = '30秒前';
  } else if (difference.inSeconds >= 30 && difference.inSeconds < 60) {
    res = '1分钟前';
  } else {
    res = showText(
        DateFormat('HH:mm:ss').format(DateTime.fromMillisecondsSinceEpoch(t)));
  }

  return res;
}
